package cn.itcast.service.impl;

import cn.itcast.dao.CourierDao;
import cn.itcast.domain.Courier;
import cn.itcast.service.CourierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.List;
import java.util.Set;

@Service
public class CourierServiceImpl implements CourierService {
    @Autowired
    private CourierDao courierDao;

    @Transactional
    //保存新增
    @Override
    public void add(Courier courier) {
        courierDao.save(courier);
    }
    //分页查询
    @Override
    public Page<Courier> pageQuery(Specification<Courier> specification, Pageable pageable) {
        return courierDao.findAll(specification,pageable);
    }

    @Override
    public void update(String id) {
        String[] split = id.split(",");
        for (String s : split) {
            courierDao.update(Integer.parseInt(s));
        }
    }


    @Override
        public void restore(String id){
            String[] split = id.split(",");
            for (String s : split) {
                courierDao.restore(Integer.parseInt(s));
            }


        }

    @Override
    public List<Courier> findNoAssocation() {
       Specification<Courier> specification= new Specification<Courier>() {
            @Override
            public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.isEmpty(root.get("fixedAreas").as(Set.class));
                return predicate;
            }
        };
       return courierDao.findAll(specification);
    }


}
